import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/api_response.dart';
import '../../models/important_day.dart';
import '../important_days_repository.dart';
import '../../services/mock_api_service.dart';

class MockImportantDaysRepository implements ImportantDaysRepository {
  static const String _storageKey = 'important_days';
  
  @override
  Future<ApiResponse<List<ImportantDay>>> getAllImportantDays() async {
    return MockApiService.simulateApiCall<List<ImportantDay>>(() async {
      final prefs = await SharedPreferences.getInstance();
      final jsonString = prefs.getString(_storageKey);
      
      if (jsonString == null) {
        final sampleData = _generateSampleData();
        await _saveToStorage(sampleData);
        return sampleData;
      }
      
      final List<dynamic> jsonList = jsonDecode(jsonString);
      return jsonList.map((json) => ImportantDay.fromJson(json)).toList();
    });
  }
  
  @override
  Future<ApiResponse<ImportantDay>> getImportantDayById(String id) async {
    return MockApiService.simulateApiCall<ImportantDay>(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final day = response.data!.firstWhere(
        (day) => day.id == id,
        orElse: () => throw Exception('未找到指定的重要日子'),
      );
      
      return day;
    });
  }
  
  @override
  Future<ApiResponse<ImportantDay>> createImportantDay(ImportantDay day) async {
    return MockApiService.simulateApiCall<ImportantDay>(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final allDays = response.data!;
      allDays.add(day);
      await _saveToStorage(allDays);
      
      return day;
    });
  }
  
  @override
  Future<ApiResponse<ImportantDay>> updateImportantDay(ImportantDay day) async {
    return MockApiService.simulateApiCall<ImportantDay>(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final allDays = response.data!;
      final index = allDays.indexWhere((d) => d.id == day.id);
      if (index == -1) {
        throw Exception('未找到要更新的重要日子');
      }
      
      allDays[index] = day;
      await _saveToStorage(allDays);
      
      return day;
    });
  }
  
  @override
  Future<ApiResponse<void>> deleteImportantDay(String id) async {
    return MockApiService.simulateVoidApiCall(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final allDays = response.data!;
      allDays.removeWhere((day) => day.id == id);
      await _saveToStorage(allDays);
    });
  }
  
  @override
  Future<ApiResponse<List<ImportantDay>>> getFutureDays() async {
    return MockApiService.simulateApiCall<List<ImportantDay>>(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final now = DateTime.now();
      final futureDays = response.data!
          .where((day) => day.date.isAfter(now) || _isSameDay(day.date, now))
          .toList()
        ..sort((a, b) => a.date.compareTo(b.date));
      
      return futureDays;
    });
  }
  
  @override
  Future<ApiResponse<List<ImportantDay>>> getPastDays() async {
    return MockApiService.simulateApiCall<List<ImportantDay>>(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final now = DateTime.now();
      final pastDays = response.data!
          .where((day) => day.date.isBefore(now) && !_isSameDay(day.date, now))
          .toList()
        ..sort((a, b) => b.date.compareTo(a.date));
      
      return pastDays;
    });
  }
  
  @override
  Future<ApiResponse<List<ImportantDay>>> getUpcomingDays() async {
    return MockApiService.simulateApiCall<List<ImportantDay>>(() async {
      final response = await getAllImportantDays();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取数据失败');
      }
      
      final now = DateTime.now();
      final upcomingDays = response.data!
          .where((day) {
            final daysUntil = day.date.difference(now).inDays;
            return daysUntil >= 0 && daysUntil <= 7;
          })
          .toList()
        ..sort((a, b) => a.date.compareTo(b.date));
      
      return upcomingDays;
    });
  }
  
  Future<void> _saveToStorage(List<ImportantDay> days) async {
    final prefs = await SharedPreferences.getInstance();
    final jsonString = jsonEncode(days.map((day) => day.toJson()).toList());
    await prefs.setString(_storageKey, jsonString);
  }
  
  List<ImportantDay> _generateSampleData() {
    return [
      ImportantDay(
        id: '1',
        title: '纪念日',
        date: DateTime.now().add(const Duration(days: 15)),
        description: '我们在一起的第一天',
        category: 'anniversary',
        emoji: '💕',
      ),
      ImportantDay(
        id: '2',
        title: '你的生日',
        date: DateTime.now().add(const Duration(days: 29)),
        description: '最重要的人的生日',
        category: 'birthday',
        emoji: '🎂',
      ),
      ImportantDay(
        id: '3',
        title: '情人节',
        date: DateTime.now().add(const Duration(days: 56)),
        description: '浪漫的情人节',
        category: 'valentine',
        emoji: '💝',
      ),
      ImportantDay(
        id: '4',
        title: '我的生日',
        date: DateTime.now().subtract(const Duration(days: 5)),
        description: '我的特别日子',
        category: 'birthday',
        emoji: '🎉',
      ),
      ImportantDay(
        id: '5',
        title: '七夕节',
        date: DateTime.now().subtract(const Duration(days: 30)),
        description: '中国的情人节',
        category: 'festival',
        emoji: '🌟',
      ),
      ImportantDay(
        id: '6',
        title: '第一次约会',
        date: DateTime.now().subtract(const Duration(days: 180)),
        description: '美好的开始',
        category: 'date',
        emoji: '🌹',
      ),
    ];
  }
  
  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }
}